package com.sjf.JavaNIO.Selector;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author <huangtang>
 * @since 2022/4/14 15:04
 **/
public class SelectorDemo1 {
    public static void main ( String[] args ) throws Exception {
        //创建Selector
        Selector selector = Selector.open ();

        //创建通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open ();

        //非阻塞
        serverSocketChannel.configureBlocking (false);

        //绑定连接
        serverSocketChannel.bind (new InetSocketAddress (9999));

        //通道注册到选择器上,并设置监听时间未：“接收”事件
        serverSocketChannel.register (selector , SelectionKey.OP_ACCEPT);

        //查询已经就绪通道操作的SelctionKey集合
        Set<SelectionKey> selectionKeys = selector.selectedKeys ();
        //遍历集合
        Iterator<SelectionKey> iterator = selectionKeys.iterator ();
        while (iterator.hasNext ()) {
            SelectionKey key = iterator.next ();
            //判断key就绪状态操作
            if ( key.isAcceptable () ) {
                //接收状态
            } else if ( key.isReadable () ) {
                //可读状态
            } else if ( key.isWritable () ) {
                //可写状态
            } else if ( key.isConnectable () ) {
                //连接状态
            }
            iterator.remove ();
        }
    }
}
